package com.xb.p29_preferencesshared;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button btn_save;
    Button btn_read;
    EditText editText;
    SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn_save=findViewById(R.id.btn_save);
        btn_read=findViewById(R.id.btn_read);
        editText=findViewById(R.id.et_name);

        btn_save.setOnClickListener(this);
        btn_read.setOnClickListener(this);

        sp=getSharedPreferences("config",MODE_PRIVATE); //文件名，访问类型
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_save:
                String saveText=editText.getText().toString();
                saveData(saveText);
                break;
            case R.id.btn_read:
                String content=sp.getString("content","");//如果没有数据，默认返回空
                Toast.makeText(this,"读取内容："+content,Toast.LENGTH_SHORT).show();
                break;
        }
    }

    public void saveData(String data){
        //使用edit方法写入
        SharedPreferences.Editor editor=sp.edit();
        editor.putString("content",data);
        editor.commit();//提交
    }
}